package com.java.architect.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class BeanHolder implements ApplicationContextAware {

    private ApplicationContext applicationContext = null;

    private final Map<String, Object> beanMap = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext context) {
        this.applicationContext = context;
    }

    public ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public <T> T getBean(Class<T> clazz) {
        String key = clazz.getName();
        if (beanMap.containsKey(key)) {
            return (T) beanMap.get(key);
        }
        synchronized (beanMap) {
            if (beanMap.containsKey(key)) {
                return (T) beanMap.get(key);
            }
            final T bean = this.getApplicationContext().getBean(clazz);
            beanMap.put(key, bean);
            return bean;
        }
    }



//    private GoodsCenterService goodsCenterService;
//    private final Object goodsCenterServiceLock = new Object();
//    public GoodsCenterService getGoodsCenterService() {
//        if (this.goodsCenterService == null) {
//            synchronized (goodsCenterServiceLock) {
//                if (this.goodsCenterService == null) {
//                    this.goodsCenterService = this.applicationContext.getBean(GoodsCenterService.class);
//                }
//            }
//        }
//        return this.goodsCenterService;
//    }
}
